package com.example.demo.controller;

import java.util.ArrayList;
import java.util.List;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.example.demo.pojo.Resource;
import com.example.demo.pojo.User;
import com.example.demo.service.ResourceService;
import com.example.demo.service.UserService;



@CrossOrigin
@Controller
@RequestMapping("/resource")
public class ResourceController {
	@Autowired
	private ResourceService resourceService;


	//web主页面加载数据的接口
	@RequestMapping(value="/main")
	@ResponseBody
	public List<Resource> findMainResource(@RequestBody Resource resource){
//		String result;
//		String resourceCategory;
		System.out.println("从前端-主页面得到的请求内容:"+resource);
		Resource resourceInfo=new Resource();
		resourceInfo.setResourceCategory(resource.getResourceCategory());
//		resourceCategory=resource.getResourceCategory();
		List<Resource>listResource=resourceService.findMainResource(resourceInfo);
		return listResource;
	}


	//android住页面加载数据的接口---亦可作为前端get请求资源List的接口
	@RequestMapping(value="/maintoandroid")
	@ResponseBody
	public List<Resource> findMainResourceToAndroid(){
		String result;
		String resourceCategory;
		Resource resourceInfo=new Resource();
		List<Resource>listResource=resourceService.findMainResourceToAndroid();
		return listResource;
	}


	//web上传视频文件的接口
	@RequestMapping(value="/uploadfile")
	@ResponseBody
	public String saveUploadFile(@RequestParam("fileName") String fileName,@RequestParam("fileCategory") String fileCategory,
			@RequestParam("userName") String userName,
			@RequestParam("fileTag1Name") String fileTag1Name,
			@RequestParam(value="file",required=false) List<MultipartFile> file,@RequestParam(value="fileCover",required=false) List<MultipartFile> fileCover,HttpServletRequest request) {
		//检查上传文件是否为空，大小是否合法
	    if(!file.isEmpty() && file.size()>0) {// && fileCover.isEmpty() && fileCover.size()>0
			System.out.println(file);
			System.out.println(fileCover);
			//resource类对象
			Resource resourceInfo=new Resource();
			//UUID随机文件名
			UUID randomUUIDname=UUID.randomUUID();
			//多个文件上传
			for(MultipartFile files:file) {
				String originalFilename=files.getOriginalFilename();
				//存储地址
				/*
				 * dirPath的方式会导致每次存储位置都存储在C:\Users\hasee\AppData\Local\Temp，
				 * 即spring boot内置tomcat的位置
				 * */
//				String dirPath=request.getServletContext().getRealPath("\\uploadfile\\");
				/*
				 * 以下方式直接将得到的上传文件指定到相应位置
				 * */
				String path = "D:\\apache-tomcat-7.0.85\\webapps\\uploadfilecover\\uploadfile";
				//存储文件的后缀
				String fileType=".mp4";
				//JAVA的IO工具File
				File filePath=new File(path);
				if(!filePath.exists()) {
					filePath.mkdirs();
				}
				String newFilename="_"+randomUUIDname+fileType;//+"_"+originalFilename  fileName+
				System.out.println("上传的视频文件存放在:" + path + newFilename);
				try {
					files.transferTo(new File(path+"\\"+newFilename));
					resourceInfo.setResourceUrl(newFilename);//dirPath+"\\"+
				}catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
					return "error";
				}
			}
			//上传文件附带的封面图
			for(MultipartFile files:fileCover) {
				List<String> list=new ArrayList<String>();
				String originalFilename=files.getOriginalFilename();
				//封面图存储地址
//				String dirPath=request.getSession().getServletContext().getRealPath("\\uploadfilecover\\");
				String path = "D:\\apache-tomcat-7.0.85\\webapps\\uploadfilecover";
				//存储文件的后缀
				String fileCoverType=".jpg";
				File filePath=new File(path);
				if(!filePath.exists()) {
					filePath.mkdirs();
				}
//				String localUrl="\\http:\\\\localhost:8080/uploadfilecover\\";localUrl+
				String newFilename="_"+randomUUIDname+fileCoverType;//+"_"+originalFilename  "Cover"+
				System.out.println("封面图存放在:" + path + newFilename);

				try {
					files.transferTo(new File(path+"\\"+newFilename));
					resourceInfo.setResourceCover(newFilename);//dirPath+"\\"+
				}catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
					return "error";
				}
			}
			
			resourceInfo.setUserName(userName);
			resourceInfo.setResourceTitle(fileName);
			resourceInfo.setResourceCategory(fileCategory);
			resourceInfo.setTag1Name(fileTag1Name);
			resourceService.saveUploadFileInfo(resourceInfo);
			
			return "success";
		}else {
			return "error:";//上传失败
		}
	}
	
	/*
	 * 返回用户浏览记录
	 * */
	@RequestMapping(value="/returnUserHistoryResource")
	@ResponseBody
	public List<Resource> findUserHistoryResource(@RequestBody List<Resource> resource){
		int returnMSG=0;
		List<Resource> msgFromDao=new ArrayList();
		System.out.println("从前端-个人中心-用户浏览记录得到的请求"+resource);
		Resource resourcelist=new Resource();
		try {
			msgFromDao=resourceService.findUserHistoryResource(resource);
			System.out.println("从dao层返回-用户浏览记录的数据:"+msgFromDao);
			if(msgFromDao!=null) {
				//成功
				returnMSG=1;
			}else {
				//失败
				returnMSG=2;
			}
		} catch (Exception e) {
			//请求异常
			System.out.println("请求异常");
			returnMSG=0;
			// TODO: handle exception
		}
		return msgFromDao;
	}

	//web搜索功能的接口，返回查询结果
	@RequestMapping(value="/returnSearchResource")
	@ResponseBody
	public List<Resource> giveSearchResultList(@RequestBody Resource resource) {
		// TODO Auto-generated method stub
		int returnMSG=0;
		List<Resource> msgFromDao=new ArrayList();
		System.out.println("从前端-搜索得到的请求:"+resource);
		List<Resource> resourcelist=new ArrayList();
		try {
			msgFromDao=(resourceService.giveSearchResultList(resource));
			System.out.println("从dao层返回搜索结果的数据:"+msgFromDao);
			if(msgFromDao!=null) {
				//成功
				returnMSG=1;
			}else {
				//失败
				returnMSG=2;
			}
		} catch (Exception e) {
			//请求失败
			System.out.println("暂时不可用，请稍后重试");
			returnMSG=0;
			// TODO: handle exception
		}
		return msgFromDao;
	}

	/*
	* 分页功能
	* 1.得到resource表中总计含有多少条数据
	* */
	@RequestMapping(value="/countResource")
	@ResponseBody
	public int countResource(@RequestBody Resource resource){
		int msgFromDao;
		msgFromDao=resourceService.countResource(resource);
		return msgFromDao;
	}

	/*
	* 主页面推荐功能接口
	* */
	@RequestMapping(value="/recommend")
	@ResponseBody
	public List<Resource> resourceForRecommend(@RequestBody int start){
		List<Resource> recommendList=resourceService.resourceForRecommend(start);
		return recommendList;
	}

	//！！！！！！！！！！！！！后台功能！！！！！！！！！！！！
	/*
	 * ��̨����ҳ���޸���Դ��Ϣ
	 * */
	@RequestMapping(value = "/backupdateresourceinfo")
	@ResponseBody
	public String backResourceUpdataInfo(@RequestBody Resource resource) {
		String returnMSG="";
		int msgFromService;
		System.out.println(resource);
		Resource resourceInfo=new Resource();
		resourceInfo.setResourceId(resource.getResourceId());
		resourceInfo.setResourceTitle(resource.getResourceTitle());
		resourceInfo.setResourceUrl(resource.getResourceUrl());
		resourceInfo.setResourceCategory(resource.getResourceCategory());
		resourceInfo.setResourceCover(resource.getResourceCover());
		resourceInfo.setTag1Name(resource.getTag1Name());
		resourceInfo.setTag2Name(resource.getTag2Name());
		resourceInfo.setTag3Name(resource.getTag3Name());
		resourceInfo.setTag4Name(resource.getTag4Name());
		resourceInfo.setTag5Name(resource.getTag5Name());
		msgFromService=resourceService.backResourceUpdataInfo(resourceInfo);
		if(msgFromService>0) {
			returnMSG="1";
		}else {
			returnMSG="请求失败，请稍后重试";
		}
		return returnMSG;
	} 
}
